package com.chinaums.xm.wechat.service.wechat;

import java.util.Optional;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.chinaums.xm.wechat.WeixinConstant;
import com.chinaums.xm.wechat.domain.wechat.AuthorizationAccessToken;
import com.chinaums.xm.wechat.service.Communicator;

import net.sf.json.JSONObject;

/**
 * 微信网页开发service
 * @author chenjf
 */
@Service
public class WebPageService {
	
	private static final Logger logger = LoggerFactory.getLogger(Communicator.class);

	@Resource
	private Communicator communicator;
	
	/**
	 * 网页授权获取AccessToken
	 * @param code
	 * @return
	 */
	public Optional<AuthorizationAccessToken> getAccessTokenByCode(final String code){
		final String url = WeixinConstant.AUTHORIZATION_ACCESS_TOKEN_URL.replace("SECRET", WeixinConstant.APP_SECRET).replace("APPID", WeixinConstant.APP_ID).replace("CODE", code);
		final Optional<String> response = communicator.getRequest(url);
		logger.info("response is:{}",response);
		if(response.isPresent()){
			final String msg = response.get();
			final JSONObject json = JSONObject.fromObject(msg);
			final AuthorizationAccessToken token = (AuthorizationAccessToken) JSONObject.toBean(json, AuthorizationAccessToken.class);
			return Optional.of(token);
		}
		return Optional.empty();
	}
	
	/**
	 * 网页授权获取用户信息
	 * @param accessToken
	 * @param openid
	 */
	public void getUserInfo(final String accessToken,final String openid){
		final String url = WeixinConstant.AUTHORIZATION_USERINFO_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID",openid);
		final Optional<String> response = communicator.getRequest(url);
		if(response.isPresent()){
			final JSONObject json = JSONObject.fromObject(response.get());
			logger.info("userInfo is:{}",json);
		}
	}
}
